package org.pjlib.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import java.util.ArrayList;

/**
 * Created by ws on 2019/04/03.
 */
public class MenuLayout extends LinearLayout implements View.OnClickListener {
    public int index;
    private OnMenuSelListener onMenuSelListener;
    private ArrayList<Menu> menus=new ArrayList<>();
    public MenuLayout(Context context) {
        this(context, null);
    }

    public MenuLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MenuLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(HORIZONTAL);
    }

    public OnMenuSelListener getOnMenuSelListener() {
        return onMenuSelListener;
    }

    public void setOnMenuSelListener(OnMenuSelListener onMenuSelListener) {
        this.onMenuSelListener = onMenuSelListener;
    }

    public void setIndex(int index) {
        this.index = index;
        if(index>= 0 && index<menus.size()){
            menus.get(index).selected(true);
            if(getOnMenuSelListener()!=null){
                getOnMenuSelListener().onMenuSel(this, menus.get(index),index);
            }
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if(child instanceof Menu){
                menus.add((Menu) child);
                child.setOnClickListener(this);
                child.setSelected(i == index);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if(getOnMenuSelListener()!=null && v instanceof Menu){
            int tag=menus.indexOf(v);
            if(index ==tag){
                getOnMenuSelListener().onRefresh(this, (Menu) v,index);
            }
            if(tag>-1 && tag!=index){
                menus.get(index).selected(false);
                index=tag;
                menus.get(index).selected(true);
                getOnMenuSelListener().onMenuSel(this, (Menu) v,index);
            }
        }
    }
    public interface OnMenuSelListener{
        void onMenuSel(MenuLayout menuLayout, Menu Menu, int index);
        void onRefresh(MenuLayout menuLayout, Menu Menu, int index);
    }
}
